import os
import json
import time
import uuid
import elu.backyard.docer.model as Model
from application import SETTINGS
from elu.base.helper import get_localtime
from elu.base.handler import BaseHandler


class DocerHandler(BaseHandler):
    def get(self):
        self.render("backyard/manage/docer.html")


class DocerAPIHandler(BaseHandler):
    def initialize(self):
        self.shelf = os.path.join(SETTINGS['static_path'], "_book")

    def get(self):
        table = Model.DocerModel()
        results = table.r()
        self.write(json.dumps(results))

        """
        nodes = []
        files = os.listdir(self.shelf)
        for f in files:
            _nodes = {}
            abs_f = os.path.join(self.shelf, f)

            # hidden files
            if not f.startswith("."):
                if os.path.isdir(abs_f):
                    try:
                        with open(os.path.join(abs_f, 'Readme.md'), 'rb') as readme:
                            readme_content = readme.read()
                    except IOError:
                        readme_content = ''
                    _nodes['name'] = f
                    _nodes['intro'] = readme_content.decode()
                nodes.append(_nodes)
        self.write(json.dumps(nodes))
        """

    def post(self):
        name = self.parse_argument('name')
        version = self.parse_argument('version')
        intro = self.parse_argument('intro')
        modified = get_localtime()
        shelf_uuid = str(uuid.uuid5(uuid.NAMESPACE_DNS, name))

        table = Model.DocerModel()
        recruit = table.c(name, intro, version, modified, shelf_uuid)

        # IO handler
        book = os.path.join(self.shelf, shelf_uuid)
        book_intro = os.path.join(book, 'Readme.md')

        if not os.path.exists(book):
            try:
                os.makedirs(book)
                intro_file = open(book_intro, 'wb')
                intro_file.write(bytes(intro, 'utf-8'))
                intro_file.close()
                io_operation = 'success'
            except Exception:
                io_operation = 'fail'
        else:
            io_operation = 'duplicate'

        if io_operation is 'fail' or io_operation is 'duplicate':
            self.write(json.dumps(io_operation))
        else:
            self.write(json.dumps(recruit))


    def patch(self):
        pass

    def delete(self, shelf_uuid):
        table = Model.DocerModel()
        table.d(shelf_uuid)
        self.write(json.dumps('success'))

        """
        name = self.parse_argument('name')
        new_name = "." + name
        book = os.path.join(self.shelf, name)
        new_book = os.path.join(self.shelf, new_name)
        if os.path.isdir(book):
            os.rename(book, new_book)
        """
